<template>
    <div class="box h100">
        <div v-show="!mode" class="table h100">
            <el-table
                    :data="tableData"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="eleId"
                    border
                    height="100%"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

                <el-table-column
                        prop="text"
                        label="菜单名"
                        width="180">
                    <!--                <template slot-scope="scope">-->
                    <!--                    <div style="width: 200px; display: inline-block">-->
                    <!--                        <el-input type="text" v-model="scope.row.text" width="250" size="mini"/>-->
                    <!--                    </div>-->
                    <!--                </template>-->
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="菜单ID"
                       width="180">
                    <!--                <template slot-scope="scope">-->
                    <!--                    <div style="width: 200px; display: inline-block">-->
                    <!--                        <el-input type="text" v-model="scope.row.name" width="250" size="mini"/>-->
                    <!--                    </div>-->
                    <!--                </template>-->
                </el-table-column>
                <el-table-column
                        prop="href"
                        label="链接"
                        width="180"
                >
                    <template slot-scope="scope">
                        {{scope.row.href || '-'}}
                        <!--                    <div style="width: 200px; display: inline-block">-->
                        <!--                        <el-input type="text" v-model="scope.row.text" width="250" size="mini"/>-->
                        <!--                    </div>-->
                    </template>
                </el-table-column>
                <el-table-column
                        label="启用"
                        width="80">
                    <template slot-scope="scope">
                        <template v-if="scope.row.open == 'y'"><i class="el-icon-check" @click="changeOpen(scope.row)"></i></template>
                        <template v-else><i class="el-icon-close" @click="changeOpen(scope.row)"></i></template>
                    </template>
                </el-table-column>
                <el-table-column>
                    <template slot-scope="scope" slot="header">
                        <div style="display: flex;">
                            <el-button type="primary" icon="el-icon-edit" @click="() => newMenu()">新建
                            </el-button>
                            <el-button type="primary" icon="el-icon-download" @click="() => backup()">备份
                            </el-button>
                            <el-upload
                                    style="margin-left: 10px;"
                                    class="upload-demo"
                                    ref="upload"
                                    :action="`${url}/menu/restore`"
                                    :auto-upload="true"
                                    :show-file-list="false"
                                    :data="{a:1,b:2}"
                                    :headers="getHeaders()"
                                    :on-success="restore">
                                <el-button slot="trigger" type="primary" icon="el-icon-upload2" >
                                    恢复
                                </el-button>
                            </el-upload>
                        </div>
                    </template>
                    <template slot-scope="scope">
                        <el-button type="primary" plain icon="el-icon-edit" @click="() => newMenu(scope.row.id)">新建
                        </el-button>
                        <el-button type="primary" plain icon="el-icon-edit" @click="editMenu(scope.row)">编辑</el-button>
                        <el-button type="danger" plain icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div v-if="mode" class="h100 ovy">
            <div class="pgh" >
                <el-page-header @back="mode = ''" :content="mode == 'add' ? '新建菜单' : '编辑菜单'">
                </el-page-header>
            </div>
            <el-form :model="data" label-width="80px" style="width:400px" :rules="rules" ref="form">
                <el-form-item label="菜单名" prop="name">
                    <el-input type="text" v-model="data.name"/>
                </el-form-item>
                <el-form-item label="所属菜单">
                    <el-select v-model="data.pid">
                        <el-option label="顶级菜单" value=""></el-option>
                        <el-option v-for="v in menuList" :label="v.path" :value="v.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="显示文字">
                    <el-input type="text" v-model="data.text" placeholder="不填写的话和菜单名一样"/>
                </el-form-item>
                <el-form-item label="图标">
                    <el-input type="text" v-model="data.icon" placeholder=""/>
                </el-form-item>
                <el-form-item label="链接">
                    <el-input type="text" v-model="data.href"/>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number type="text" v-model="data.sort"/>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch
                            v-model="data.open"
                            active-value="y"
                            inactive-value="n"
                            active-text="开启"
                            inactive-text="关闭"/>
                </el-form-item>

                <div style="text-align: center">
                    <el-button type="primary" icon="el-icon-check" @click="() => submitForm(true)" :loading="saving">
                        保存关闭
                    </el-button>
                    <el-button type="primary" icon="el-icon-check" @click="() => submitForm(false)" :loading="saving" v-if="mode == 'add'">
                        保存继续新建
                    </el-button>
                </div>
            </el-form>
        </div>
    </div>
    <!--        <el-tabs class="tab" v-model="currentTab">-->
    <!--            <el-tab-pane label="用户管理" name="first">-->
    <!--    <div style="margin-bottom: 10px;">-->
    <!--        <router-link to="/menu/edit">123</router-link>-->
    <!--        <el-button type="primary" icon="el-icon-edit" @click="newMenu">新建</el-button>-->
    <!--    </div>-->
    <!--            </el-tab-pane>-->
    <!--            <el-tab-pane v-if="currentTab != 'first'" :label="secondText" name="second">-->
    <!--                <el-form :model="data" label-width="80px" style="width:400px" :rules="rules" ref="form">-->
    <!--                    <el-form-item label="菜单名" prop="name">-->
    <!--                        <el-input type="text" v-model="data.name"/>-->
    <!--                    </el-form-item>-->
    <!--                    <el-form-item label="所属菜单">-->
    <!--                        <el-select v-model="data.pid">-->
    <!--                            <el-option label="顶级菜单" value=""></el-option>-->
    <!--                            <el-option v-for="v in menuList" :label="v.path" :value="v.id"></el-option>-->
    <!--                        </el-select>-->
    <!--                    </el-form-item>-->
    <!--                    <el-form-item label="显示文字">-->
    <!--                        <el-input type="text" v-model="data.text" placeholder="不填写的话和菜单名一样"/>-->
    <!--                    </el-form-item>-->
    <!--                    <el-form-item label="链接">-->
    <!--                        <el-input type="text" v-model="data.href"/>-->
    <!--                    </el-form-item>-->
    <!--                    <el-form-item label="排序">-->
    <!--                        <el-input-number type="text" v-model="data.sort"/>-->
    <!--                    </el-form-item>-->
    <!--                    <el-form-item label="是否启用">-->
    <!--                        <el-switch-->
    <!--                                v-model="data.open"-->
    <!--                                active-value="y"-->
    <!--                                inactive-value="n"-->
    <!--                                active-text="开启"-->
    <!--                                inactive-text="关闭"/>-->
    <!--                    </el-form-item>-->

    <!--                    <div style="text-align: center">-->
    <!--                        <el-button type="primary" icon="el-icon-check" @click="() => submitForm(true)" :loading="saving">-->
    <!--                            保存关闭-->
    <!--                        </el-button>-->
    <!--                        <el-button type="primary" icon="el-icon-check" @click="() => submitForm(false)" :loading="saving">-->
    <!--                            保存继续新建-->
    <!--                        </el-button>-->
    <!--                    </div>-->
    <!--                </el-form>-->
    <!--            </el-tab-pane>-->
    <!--        </el-tabs>-->
</template>

<script>
    import $ from "jquery";
    import download from "../libs/download"
    import {formatDate} from "../libs/date"

    export default {
        data() {
            return {
                mode: "",
                tableData: [],
                menuList: [],
                data: {},
                rules: {
                    name: {required: true, message: '请输入菜单名', trigger: 'blur'},
                },
                saving: false,
                url: window.Env.ApiUrl//this.$cookies.get("bpm-url") || ""
            }
        },
        methods: {
            getHeaders(){
                return{
                    "bpm-token": localStorage.getItem("bpm-token")
                }
            },
            load() {
                $.get("/menu/menu?type=all", (js) => {
                    var _menu = js.data || [];
                    //计算menu路径
                    var walk = (path, deep, children) => {
                        children.forEach(e => {
                            this.menuList.push(e);
                            e.deep = deep + 1;
                            e.path = "　".repeat(deep) + e.name;
                            e.eleId = e.id + "fff";
                            // console.log(e.path)
                            // e.path = "\t" + e.path;//"(null == path ? "" : path + ".") + e.name;
                            walk(e.path, e.deep, e.children || []);
                        });
                    };
                    walk(null, 0, _menu);
                    this.tableData = _menu
                    console.log(_menu);
                })
            },
            newMenu(pid) {
                this.mode = "add";
                this.data =  {
                    pid: pid || "",
                    open: "y"
                }
            },
            editMenu(v) {
                v.pid = v.pid || "";
                this.mode = "edit";
                this.data = v;
            },
            submitForm(close) {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.saving = true;
                        //日掉children
                        var d = Object.assign({},this.data);
                        delete d.children;
                        $.ajax({
                            url: "/menu/save",
                            method: "post",
                            data: JSON.stringify(d),
                            dataType:"json",
                            headers:{
                                "content-type":"application/json"
                            },
                            success: (data) => {
                                if(!data.success){
                                    this.$notify.error(data.errMessage)
                                    return
                                }
                                this.load();
                                if(close){
                                    this.mode = "";
                                } else {
                                    this.newMenu(this.data.pid);
                                    this.$notify.success({
                                        title:"提示",
                                        message: "保存成功，请继续新建"
                                    })
                                }
                            },
                            complete: () =>{
                                this.saving = false;
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            async del(v){
                try{
                    await this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                    $.get("/menu/del", {id: v.id},  (msg) => {
                        this.load();
                        this.$notify.success({
                            title: '提示',
                            message: '删除成功!'
                        });
                    }, "json");
                } catch(e){}
            },

            /**
             * 更改状态
             */
            changeOpen(v){
                v.open = v.open === 'y' ? 'n' : 'y';
                $.get("/menu/changeOpen", {id:v.id,open:v.open}, json => {});
            },

            backup(){
                download(`${this.url}/menu/backup?bpm-token=${localStorage.getItem("bpm-token")}`, `menu-${formatDate(new Date(), "yyyy-MM-dd")}.data`);
                // $.ajax({
                //     url:"/menu/backup",
                //     success: download.bind(true, "application/octet-stream", "menu-backup.data")
                // }).then(e => {
                //     this.$notify.success({
                //         message: "备份成功"
                //     })
                // })
            },
            restore(){
                this.load();
                this.$notify.success({message:"恢复成功"})
            }

        },
        mounted(){
            this.load()
        }
        // beforeRouteEnter(to, from, next){
        //     next(t => {
        //         if(from.name === 'menu.edit'){
        //             t.load()
        //         }
        //     });
        // }
    };
</script>
<style lang="less" scoped>
    .el-icon-check{
        color: #67C23A;
        font-size: 20px;
        cursor: pointer;
    }
    .el-icon-close{
        color: #F56C6C;
        font-size: 20px;
        cursor: pointer;
    }
    .box{
        /*height: 100%;*/
        /*overflow: hidden;*/
        /*.table{*/
        /*    height: 100%;*/
        /*overflow-y: auto;*/
        /*}*/
    }
    /*.tab{*/
    /*    display: flex;*/
    /*    flex-direction: column;*/
    /*    height: 100%;*/

    /*    .el-tabs__content{*/
    /*        flex: 1;*/
    /*        overflow-y: auto;*/
    /*    }*/
    /*}*/
</style>